#pragma once

#include <iostream>
#include <cstdio>
#include <string>
#include <fstream>
#include <sstream>
#include <memory>
#include <filesystem> //C++17
#include <unistd.h>
#include <time.h>
#include <pthread.h>

namespace Log_M
{
    std::string Default_path = "./log";
    std::string Default_name = "/log.txt";
    std::string CurrentTime()
    {
        time_t time = ::time(nullptr);
        struct tm curr;
        localtime_r(&time, &curr);
        char buffer[1024];
        snprintf(buffer, sizeof(buffer), "%4d-%02d-%02d %02d:%02d:%02d",
                 curr.tm_year + 1900,
                 curr.tm_mon + 1,
                 curr.tm_mday,
                 curr.tm_hour,
                 curr.tm_min,
                 curr.tm_sec);

        return buffer;
    }

    // 日志的等级
    enum class Log_Level
    {
        DEBUG,
        INFO,
        WARNING,
        ERROR,
        FATAL
    };
    // 等级的显示
    std::string Log_Level_Display(Log_Level level)
    {
        switch (level)
        {
        case Log_Level::DEBUG:
            return "DEBUG";
        case Log_Level::INFO:
            return "INFO";
        case Log_Level::WARNING:
            return "WARNING";
        case Log_Level::ERROR:
            return "ERROR";
        case Log_Level::FATAL:
            return "FATAL";
        default:
            return "None";
        }
    }
    // 利用基类的virtual纯虚函数，来进行子类重写实现功能
    class Log_Strategy
    {
    public:
        virtual ~Log_Strategy() = default;
        virtual void Log_Way(const std::string &messaeg) = 0;
    };

    // 方法一：利用控制台打印，即是屏幕进行打印
    class Log_Strategy_One : public Log_Strategy
    {
    public:
        void Log_Way(const std::string &message)
        {
            pthread_mutex_t lock;
            pthread_mutex_init(&lock, nullptr);
            pthread_mutex_lock(&lock);
            std::cout << message << std::endl;
            pthread_mutex_unlock(&lock);
            pthread_mutex_destroy(&lock);
        }
    };

    // 方法二：利用文件流进行存储在文件里面
    class Log_Strategy_Two : public Log_Strategy
    {
    private:
        std::string _path;
        std::string _name;

    public:
        Log_Strategy_Two(const std::string &path = Default_path, const std::string &name = Default_name)
            : _path(path), _name(name)
        {
            // 确认文件path是存在的
            if (std::filesystem::exists(_path))
            {
                return;
            }
            try
            {
                std::filesystem::create_directories(_path);
            }
            catch (std::filesystem::filesystem_error &e)
            {
                std::cerr << e.what() << '\n';
            }
        }
        ~Log_Strategy_Two() {}

        void Log_Way(const std::string &message)
        {
            pthread_mutex_t lock;
            pthread_mutex_init(&lock, nullptr);
            pthread_mutex_lock(&lock);
            std::string log = _path + _name;
            std::ofstream out(log, std::ios::app);
            if (!out.is_open())
            {
                return;
            }
            out << message << "\n";
            out.close();
            pthread_mutex_unlock(&lock);
            pthread_mutex_destroy(&lock);
        }
    };

    class Logger
    {
    private:
        std::shared_ptr<Log_Strategy> _strategy; // 日志刷新的策略方案
    public:
        Logger()
        {
            _strategy = std::make_shared<Log_Strategy_One>();
        }
        void Enable_ConsoleLog()
        {
            _strategy = std::make_shared<Log_Strategy_One>();
        }
        void Enable_FileLog()
        {
            _strategy = std::make_shared<Log_Strategy_Two>();
        }
        ~Logger() {}

        class Log_Message
        {
        public:
            Log_Message(Log_Level level, const std::string &filename, int line, Logger &logger)
                : _currtime(CurrentTime()),
                  _level(level),
                  _pid(::getpid()),
                  _filename(filename),
                  _line(line),
                  _logger(logger)
            {
                // 字符缓冲区
                std::stringstream ssbuffer;
                ssbuffer << "[" << _currtime << "] "
                         << "[" << Log_Level_Display(_level) << "] "
                         << "[" << _pid << "] "
                         << "[" << _filename << "] "
                         << "[" << _line << "] - ";
                _loginfo = ssbuffer.str();
            }

            template <typename T>
            void operator<<(const T &info)
            {
                std::stringstream ss;
                ss << info;
                _loginfo += ss.str();
            }

            //析构是进行日志的打印！！！！
            ~Log_Message()
            {
                if (_logger._strategy)
                {
                    _logger._strategy->Log_Way(_loginfo);
                }
            }

        private:
            std::string _currtime; // 当前日志的时间
            Log_Level _level;      // 日志等级
            pid_t _pid;            // 进程pid
            std::string _filename; // 源文件名称
            int _line;             // 日志所在的行号
            Logger &_logger;       // 负责根据不同的策略进行刷新
            std::string _loginfo;  // 一条完整的日志记录
        };

        //就是要拷贝,故意的拷贝
        Log_Message operator()(Log_Level level, const std::string &filename, int line)
        {
            return Log_Message(level, filename, line, *this);
        }

    };

    Logger logger;

#define Log(Level) logger(Level, __FILE__, __LINE__)
#define ENABLE_CONSOLE_LOG() logger.Enable_ConsoleLog()
}